package chaw.android.train;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import chaw.android.util.HttpRequestManager;
import chaw.android.util.Preferences;
import chaw.android.util.ServerURL;
import android.app.ListActivity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

public class ModifyChatListActivity extends ListActivity{
	private ModifyChatListItemAdapter nadapter;
	private ArrayList<JSONObject> json_list;
	private ImageView imageView1;
	private ImageButton btnCreateRoom;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chat_list);
		
		imageView1 = (ImageView) findViewById(R.id.imageView1);
		btnCreateRoom = (ImageButton) findViewById(R.id.btnCreateRoom);
		
		imageView1.setBackgroundResource(R.drawable.btn_close);
		btnCreateRoom.setBackgroundResource(R.drawable.btn_ok);
		
		imageView1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		btnCreateRoom.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		setListView();
	}
	
	private void setListView(){
		Bundle bundle = getIntent().getExtras();
		try {
			json_list = new ArrayList<JSONObject>();
			JSONArray json_arr = new JSONArray(bundle.getString("modify_list"));
			for(int i = 0 ; i < json_arr.length(); i++){
				JSONObject json_obj = (JSONObject) json_arr.get(i);
				json_list.add(json_obj);
			}
			nadapter = new ModifyChatListItemAdapter(getBaseContext(), R.layout.modify_chat_list_row, json_list);
		    getListView().setAdapter(nadapter);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	private class ModifyChatListItemAdapter extends ArrayAdapter<JSONObject>{
		private ArrayList<JSONObject> items;
		int layout;
		
		public ModifyChatListItemAdapter(Context ctx, int layout, ArrayList<JSONObject> data){
			super(ctx, layout, data);
			this.items = data;
			this.layout = layout;
		}
		
		@Override
		public View getView(final int position, View convertView, ViewGroup parent){
			View v = convertView;
			if(v == null){
				LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = li.inflate(layout, null);
			}
			JSONObject eachRoom = items.get(position);
			
			if(eachRoom != null){
				try {
					final String room_id = eachRoom.getString("room_id");
					JSONArray usersInRoom = eachRoom.getJSONArray("users");
					JSONObject someUser = usersInRoom.getJSONObject(0);
					if(someUser.getString("user_id").equalsIgnoreCase(Preferences.getValue(getBaseContext(), "user_id")) && usersInRoom.length() > 1)
						someUser = usersInRoom.getJSONObject(1);

					String speakers;
					if(usersInRoom.length() > 2)
						speakers = someUser.getString("nick_name") + "님 외 " + ( usersInRoom.length() - 2) + "명";
					else
						speakers = someUser.getString("nick_name") + "님";
					((TextView)v.findViewById(R.id.speakers)).setText(speakers);
					
					((Button)v.findViewById(R.id.btnDelete)).setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							items.remove(position);
							UploadAsynkTask task = new UploadAsynkTask();
							String[] params = new String[]{ ServerURL.exit_room, "user_id", Preferences.getValue(getBaseContext(), "user_id"),
										"uuid_check", Preferences.getValue(getBaseContext(), "uuid"), "room_id", room_id};
							task.execute(params);
							nadapter.notifyDataSetChanged();
						}
					});
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return v;
		}
	}
	
	private class UploadAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
		}
	}
}
